﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using WeChatSDK.WeChatDto.ServerTokenVerification;

namespace WeChatSDK.WeChatServiceComponent.ServerTokenVerification
{
    /// <summary>
    /// 服务器Token验证服务
    /// </summary>
    public class ServerTokenVerificationService
    {
        /// <summary>
        /// 验证服务器Token是否正确
        /// </summary>
        /// <param name="signature">签名</param>
        /// <param name="timestamp">时间截</param>
        /// <param name="nonce">随机数</param>
        /// <param name="echostr">随机字符串</param>
        /// <param name="token">服务器Token</param>
        /// <returns></returns>
        public static bool CheckServerToken(string signature,string timestamp,string nonce, string echostr,string token)
        {
            ServerTokenVerificationDto serverTokenVerificationDto = new ServerTokenVerificationDto();
            serverTokenVerificationDto.Signature = signature;
            serverTokenVerificationDto.Timestamp = timestamp;
            serverTokenVerificationDto.Nonce = nonce;
            serverTokenVerificationDto.EchoStr = echostr;
            serverTokenVerificationDto.Token = token;
            return CheckServerToken(serverTokenVerificationDto);
        }
        /// <summary>
        /// 验证服务器Token是否正确
        /// </summary>
        /// <param name="serverTokenVerificationDto">服务器Token验证模型</param>
        /// <returns></returns>
        public static bool CheckServerToken(ServerTokenVerificationDto serverTokenVerificationDto)
        {
            List<string> list = new List<string>();
            list.Add(serverTokenVerificationDto.Token);
            list.Add(serverTokenVerificationDto.Timestamp);
            list.Add(serverTokenVerificationDto.Nonce);
            list.Sort();
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] sign = sha1.ComputeHash(Encoding.UTF8.GetBytes(string.Join("", list)));
            sha1.Clear();
            string output = BitConverter.ToString(sign);
            output = output.Replace("-", "");
            output = output.ToLower();
            return output.Equals(serverTokenVerificationDto.Signature);
        }
    }
}
